#!/usr/bin/python
#coding: utf-8
"""
@Name:03_ssh登录模块pexpect.py
@Data:20-5-3
@Author:181
"""
import  pexpect
# #1. 通过pexpect执行指令
# (command_output, exitstatus)= pexpect.run('hostname',withexitstatus=1)
# command_output = command_output.decode('utf-8')
# if exitstatus == 0:
#     print('命令执行成功',command_output)
# else:
#     print('命令执行失败',command_output)

# command  =  'ssh -p22 root@172.25.135.13'
# child = pexpect.spawn(command,timeout=2)
# match_index = child.expect(['continue connecting(yes/no)?','password:'])
# print(match_index)
# if match_index == 0:
#   child.sendline('yes')
#   child.expect('password:')
#   child.sendline('redhat')
# elif match_index  == 1:
#      child.sendline('redhat')
#
# login_index = child.expect(['Welcome',pexpect.EOF,pexpect.TIMEOUT])
# print(login_index)
# if login_index == 0:
#     print('登录成功')
#     child.interact()
# elif login_index == 1:
#     print('登录失败')
# elif login_index == 2:
#     print('登录失败：超时')



def login_ssh_password(user,host, password, port=22):
    command = 'ssh -p%s %s@%s' %(port, user, host)
    # spawn开启一个子进程处理交互式操作
    child = pexpect.spawn(command, timeout=15)
    # 匹配交互信息, 返回的是匹配到信息的索引
    match_index = child.expect(['continue connecting (yes/no)?', 'password:'])
    print(match_index)
    # 如果索引是0， 代表第一次连接， 先输入yes， 再输入密码
    if match_index == 0:
        # print("第一次登录")
        child.sendline('yes')
        child.expect(['password:'])
        child.sendline(password)
    # 如果索引是1， 代表不是第一次登录， 则直接输入密码即可。
    elif match_index == 1:
        # print("非第一次登录")
        child.sendline(password)


    login_index = child.expect(['Welcome', pexpect.EOF, pexpect.TIMEOUT])
    print(login_index)
    if login_index == 0:
        print("用户登录成功")
        # 进入远程服务器的命令行
        child.interact()
    elif login_index == 1:
        print("登录失败: Logout")
    elif login_index == 2:
        print("登录失败: 超时")



if __name__ == '__main__':
    login_ssh_password(user='root', host='172.25.135.13', password='redhat')